package com.junxonline.instant.terminal.netty.handler;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

@Log4j2
@Component
@Sharable
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    /**
     * 心跳超时事件处理
     *
     * @param context 上下文
     * @param event   事件
     * @throws Exception Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext context, Object event) throws Exception {
        if (event instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) event).state();
            // 读取超时事件
            if (state == IdleState.READER_IDLE) {
                // 主动关闭连接
                context.channel().close();
                log.warn("客户端 -> " + context.channel().remoteAddress() + " 读取超时 -> " + state + " 连接被关闭");
            }
        } else {
            super.userEventTriggered(context, event);
        }
    }

}
